package ru.pb.game.network.engine.client.packets.receivable;

import java.util.concurrent.locks.ReentrantLock;

import org.apache.log4j.Logger;

import ru.pb.game.dao.CheckPlayerDAO;
import ru.pb.game.data.xml.holders.ChannelHolder;
import ru.pb.game.network.engine.client.packets.FromClientToGameServerPacket;
import ru.pb.game.network.engine.client.packets.sendable.PROTOCOL_LOBBY_CREATE_NICK_NAME_ACK;
import ru.pb.game.objects.model.CHANNEL;
import ru.pb.game.objects.model.players.Player;
import ru.pb.global.dao.DAOManager;

/**
 * @author: DarkSkeleton
 */
public class PROTOCOL_LOBBY_CREATE_NICK_NAME_REQ extends FromClientToGameServerPacket
{
	private static final Logger _log = Logger.getLogger(PROTOCOL_LOBBY_CREATE_NICK_NAME_REQ.class);
	private static final ReentrantLock _lock = new ReentrantLock();

	private static CheckPlayerDAO _dao = DAOManager.getDAOImpl(CheckPlayerDAO.class);

	private int EVENT_ERROR_EVENT_DUPLICATE_NICK = 0x80000113;

	private int _unk_1;
	private int _name_lenght; // name_lenght - 1
	private String _name;

	public PROTOCOL_LOBBY_CREATE_NICK_NAME_REQ()
	{}

	@Override
	public void readImpl()
	{
		_unk_1 = readH();
		_name_lenght = readC();
		_name = readS(_name_lenght - 1);
	}

	@Override
	public void runImpl()
	{
		Player newChar = null;
		_lock.lock();
		try
		{
			if(_dao.getObjectIdByName(_name) > 0)
			{
				sendPacket(new PROTOCOL_LOBBY_CREATE_NICK_NAME_ACK(EVENT_ERROR_EVENT_DUPLICATE_NICK));
				return;
			}

			newChar = Player.create(getClient(), _name);
			if(newChar != null)
			{
				CHANNEL ch = ChannelHolder.getChannel(getClient().getChannelId());
				if( !ch.getAllPlayers().contains(newChar.getObjectId()))
					ch.addPlayer(newChar);

				sendPacket(new PROTOCOL_LOBBY_CREATE_NICK_NAME_ACK(0));
				return;
			}
		}
		finally
		{
			_lock.unlock();
		}
		sendPacket(new PROTOCOL_LOBBY_CREATE_NICK_NAME_ACK(0x4a100080)); // Сетевые неполадки
	}
}